package com.example.mvvm.demo

import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import androidx.activity.viewModels
import androidx.fragment.app.commit
import androidx.lifecycle.Observer
import com.example.base.adapter.LifecycleAdapter
import com.example.base.adapter.holder.RVHolder
import com.example.base.adapter.into
import com.example.base.base.BaseActivity
import com.example.base.base.BaseViewModel
import com.example.base.base.util.bindView
import com.example.base.eventlivedata.EventLiveData
import com.example.mvvm.R
import com.example.mvvm.databinding.ActivityMainBinding
import kotlinx.android.synthetic.main.item_test.view.*
import kotlinx.coroutines.delay

/**
 *  使用委托的ViewBinding Activity
 */
class MainActivity : BaseActivity(R.layout.activity_main) {

    private val binding: ActivityMainBinding by bindView()
    private val viewModel by viewModels<MainActivityViewModel>()
    private val adapter = MainActivityAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.btnNext.setOnClickListener {
            val intent = Intent(this, BindingActivity::class.java)
            startActivity(intent)
        }
        binding.btnDialog.setOnClickListener {
            BlankDialog().show(supportFragmentManager, "")
        }
        supportFragmentManager.commit { add(binding.fragment1.id, BlankFragment()) }
        adapter.into(binding.recy)
        adapter.addItem(0,viewModel.name)

    }

}

class MainActivityViewModel: BaseViewModel() {

    private val repository by lazy { MainActivityRepository() }

    val name = EventLiveData<String>()
}

class MainActivityRepository {

    suspend fun refreshName(name: EventLiveData<String>) {
        for (i in 1 .. 10) {
            delay(1000)
            name.submitValue("大猩猩${i}号")
        }
    }
}

// 不用ViewBinding的
class MainActivityAdapter : LifecycleAdapter<EventLiveData<String>, RVHolder>(R.layout.item_test) {

    override fun fillData(rvHolder: RVHolder, position: Int, model: EventLiveData<String>?) {
        super.fillData(rvHolder, position, model)
        val item = model ?: return
        val tvName = rvHolder.getView<TextView>(R.id.tv_name)  //或者这样拿到控件
        item.observeSticky(this, Observer {
            rvHolder.itemView.tv_name.text = it
        })
    }
}

